class HomeController < ApplicationController
  GAME_PATH = '~/Game/Game/bin/Release/Game.exe'

  def index
  end

  def new_game
    lock_game_id

    last_id = $redis.get 'last_id'
    $redis.set('last_id', '0') if not last_id

    game_id = (last_id.to_i + 1).to_s
    
    session[:game_id] = game_id
    system "mono #{GAME_PATH} -remote #{game_id} &"

    $redis.set 'last_id', game_id

    unlock_game_id
    respond_to do |format|
      format.json{ render :json => true.to_json }
    end
  end
  
  def map_infos
    game_id = session[:game_id]
    map_key = "map:#{game_id}"
    map = {:width => $redis.hget(map_key, "width"), :height => $redis.hget(map_key, "height")}
    #
    respond_to do |format|
      format.json{ render :json => map.to_json }
    end
  end
  
  def slime_datas
    game_id = session[:game_id]
    slime_key = "slimes:#{game_id}"
    slimes = {:my => $redis.hget(slime_key, "my"), :enemy => $redis.hget(slime_key, "enemy")}
    respond_to do |format|
      format.json{ render :json => slimes.to_json }
    end
  end
  
  def slime_action
    fun_key = "function:#{session[:game_id]}"
    #order = {:function => "move", :id=> params[:id], :x => params[:x], :y => params[:y]}.to_json
    $redis.set fun_key, params.to_json
    
    respond_to do |format|
      format.json{ render :json => params.to_json }
    end
  end

  def end_turn
    game_id = session[:game_id]
    $redis.set done_key(game_id), "yes"
    respond_to do |format|
      format.json{ render :json => true.to_json }
    end
  end

  def wait
    game_id = session[:game_id]
    ai_end = ($redis.get(done_key(game_id)) == 'no')
    log = nil
    rget = $redis.get ailog_key(game_id)
    log = JSON.parse(rget) if rget
    obj = {'ai_end' => ai_end, 'ai_log' => log}
    respond_to do |format|
      format.json{ render :json => obj.to_json }
    end
  end

  private
  def lock_game_id
    while $redis.get "game_id_lock"
      sleep (0.01).second
    end
    $redis.set "game_id_lock", true
  end

  def unlock_game_id
    $redis.del "game_id_lock"
  end

  def done_key game_id
    return "done:#{game_id}"
  end

  def ailog_key game_id
    return "ailog:#{game_id}"
  end

end
